<template>
  <el-dialog v-bind="$attrs" v-on="$listeners">
    <el-form
      :model="params"
      :rules="studentRules"
      ref="form"
      label-width="100px"
      size="mini"
    >
      <el-form-item label="学生姓名:" prop="student_name">
        <el-input v-model="params.student_name"></el-input>
      </el-form-item>
      <el-form-item label="联系电话:" prop="student_number">
        <el-input v-model="params.student_number"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱:" prop="student_email">
        <el-input v-model="params.student_email"></el-input>
      </el-form-item>
      <el-form-item label="出生日期:" prop="student_birthday">
        <el-date-picker
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          v-model="params.student_birthday"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="性别:" prop="student_sex">
        <el-radio-group v-model="params.student_sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属班级:" prop="student_class_id">
        <el-select clearable v-model="params.student_class_id">
          <el-option label="请选择班级" value="" disabled></el-option>
          <el-option
            v-for="c in classes"
            :key="c.class_id"
            :label="c.class_name"
            :value="c.class_id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="mini" @click="change()">取消</el-button>
      <el-button type="primary" size="mini" @click="confirm()">添加</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { selectClassOptions } from "@/api";
import studentRules from "@/rules/studentRules";
import { insertNewStudent } from "@/api/student";

export default {
  data() {
    return {
      classes: [],
      studentRules,
      params: {
        student_number: "",
        student_name: "",
        student_email: "",
        student_birthday: "",
        student_sex: "",
        student_class_id: "",
      },
    };
  },
  methods: {
    async initOptions() {
      let { data } = await selectClassOptions();
      this.classes = data;
    },
    change() {
      this.$emit("update:visible", false);
      this.$refs.form.resetFields();
      this.$refs.form.clearValidate();
    },
    async confirm() {
      await this.$refs.form.validate();
      await insertNewStudent(this.params);
      this.$emit("reload");
      this.$emit("update:visible", false);
      this.$refs.form.resetFields();
      this.$refs.form.clearValidate();
    },
  },
  created() {
    this.initOptions();
  },
};
</script>

<style lang="scss" scoped>
.el-select,
.el-date-editor {
  display: block;
  flex-grow: 1;
  width: 100%;
}
</style>
